import { login, reg, add, getList, getSingle, update } from './request'
import { useUserStore } from '../stores/user'

// 电影对应的typeIndex
const MOVIE_TYPE_INDEX = 3
// 评论对应的typeIndex  
const COMMENT_TYPE_INDEX = 4

// 数据格式转换函数：v0格式 → 后端格式
export function convertToBackendFormat(movieData: any) {
  return {
    title: movieData.title,
    desc: movieData.description,
    actors: Array.isArray(movieData.cast) ? movieData.cast.join(',') : movieData.cast,
    picPaths: movieData.poster,
    playUrl: movieData.playUrl || '',
    typeIndex: MOVIE_TYPE_INDEX,
    userid: movieData.userid
  }
}

// 数据格式转换函数：后端格式 → v0格式
export function convertToFrontendFormat(backendData: any) {
  return {
    id: backendData.id,
    title: backendData.title,
    description: backendData.desc || '',
    genre: '电影', // 后端没有genre字段，设为默认值
    year: new Date().getFullYear(), // 后端没有year字段，设为当前年份
    rating: 8.0, // 后端没有rating字段，设为默认值
    poster: backendData.picPaths || '/placeholder.svg?height=400&width=300',
    director: '未知导演', // 后端没有director字段
    cast: backendData.actors ? backendData.actors.split(',') : [],
    duration: '未知时长', // 后端没有duration字段
    playUrl: backendData.playUrl || '',
    userid: backendData.userid,
    addedTime: backendData.addedTime,
    authorName: backendData.authorName || '匿名用户'
  }
}

// 用户注册
export async function registerUser(userData: any) {
  try {
    const result = await reg(userData)
    return result
  } catch (error) {
    console.error('注册失败:', error)
    return false
  }
}

// 用户登录
export async function loginUser(userData: any) {
  try {
    const result = await login(userData)
    return result
  } catch (error) {
    console.error('登录失败:', error)
    return null
  }
}

// 获取电影列表
export async function getMovieList() {
  try {
    const result = await getList(MOVIE_TYPE_INDEX)
    if (result && Array.isArray(result)) {
      return result.map(item => convertToFrontendFormat(item))
    }
    return []
  } catch (error) {
    console.error('获取电影列表失败:', error)
    return []
  }
}

// 添加电影
export async function addMovie(movieData: any) {
  try {
    const userStore = useUserStore()
    const submitData = {
      ...convertToBackendFormat(movieData),
      userid: userStore.user?.id || null
    }
    
    const result = await add(submitData)
    return result
  } catch (error) {
    console.error('添加电影失败:', error)
    return false
  }
}

// 获取单个电影详情
export async function getMovieDetail(movieId: string) {
  try {
    const result = await getSingle(movieId, MOVIE_TYPE_INDEX)
    if (result) {
      return convertToFrontendFormat(result)
    }
    return null
  } catch (error) {
    console.error('获取电影详情失败:', error)
    return null
  }
}

// 获取电影评论列表
export async function getMovieComments(movieId: string) {
  try {
    // 确保传递正确的参数格式
    const result = await getList(COMMENT_TYPE_INDEX, parseInt(movieId), '电影')
    console.log('获取评论结果:', result) // 调试用
    return result || []
  } catch (error) {
    console.error('获取评论失败:', error)
    return []
  }
}

// 添加电影评论
export async function addMovieComment(movieId: string, commentData: any) {
  try {
    const userStore = useUserStore()
    const submitData = {
      body: commentData.content,
      userid: userStore.user?.id || null,
      replyType: '电影',
      articleid: movieId,
      typeIndex: COMMENT_TYPE_INDEX
    }
    
    const result = await add(submitData)
    return result
  } catch (error) {
    console.error('添加评论失败:', error)
    return false
  }
}

// 更新电影
export async function updateMovie(movieId: string, movieData: any) {
  try {
    const userStore = useUserStore()
    const submitData = {
      id: movieId,
      ...convertToBackendFormat(movieData),
      userid: userStore.user?.id || null
    }
    
    const result = await update(submitData)
    return result
  } catch (error) {
    console.error('更新电影失败:', error)
    return false
  }
} 